package com.hethongviet.job.helpers.sound;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import android.media.MediaPlayer;

public final class SoundPlay
{
	private static MediaPlayer _player = new MediaPlayer();

	public static final int play(File audioFile)
	{
		FileInputStream fileInputStream;
		try
		{
			fileInputStream = new FileInputStream(audioFile);
			return play(fileInputStream.getFD());
		} catch (FileNotFoundException e)
		{			
			e.printStackTrace();
			return -1;
		} catch (IOException e)
		{
			e.printStackTrace();
			return -1;
		}

	}

	public static final int play(FileDescriptor fileDescriptor)
	{
		if (_player == null) _player = new MediaPlayer();
		try
		{
			_player.setDataSource(fileDescriptor);
		} catch (IllegalArgumentException e)
		{
			e.printStackTrace();
		} catch (IllegalStateException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
		play();
		return _player.getDuration();
	}

	public static boolean isPlaying()
	{
		if(_player != null && _player.isPlaying()) return true;
		return false;
	}
	
	private static void play()
	{
		if (_player == null) _player = new MediaPlayer();

		try
		{
			_player.prepare();
		} catch (IllegalStateException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
		_player.start();

	}

	public static void stop()
	{
		if (_player != null)
		{
			_player.stop();
			_player.release();
			_player = null;
		}
	}
}
